﻿using BusinessLayer.VDataEntities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Xml;
using System.Xml.Linq;

namespace CustomerServiceCenter.Helper
{
    public class ImportLogToXML
    {
        private static int LogID = 1; 
        private static XmlDocument xmldoc = new XmlDocument();
        //private static XmlElement xmlElement;

        private static XmlElement userElement;


        public static void InsertXML(List<long> list,string path, string userName)
        {
            
            if (File.Exists(path))
            {
                XDocument doc = XDocument.Load(path);
                XElement historys = GetInsertHistory(userName,doc);
                //若存在该人,即该人已经上传过
                if(historys!=null){
                    XElement logElement = (XElement)((XElement)((XElement)doc.FirstNode).FirstNode).FirstNode; ;
                   logElement.AddAfterSelf(
                       new XElement("Log",
                        new XElement("InsertDate", DateTime.Now.ToString("F")),
                        GetContent(list)
                        ));
                   doc.Save(path);
                }
                else
                {
                    XElement user =(XElement)((XElement)doc.FirstNode).FirstNode;
                    user.AddBeforeSelf(new XElement("User",
                                new XAttribute("id", userName),
                                new XElement("Log",
                                    new XElement("InsertDate", DateTime.Now.ToString("F")),
                                    GetContent(list)
                            )));
                    doc.Save(path);
                }
            }else{
                //如果没有改文档
                var doc = new XDocument(
                            new XElement("InsertHistory",
                            new XElement("User",
                                new XAttribute("id", userName),
                                new XElement("Log",
                                    new XElement("InsertDate", DateTime.Now.ToString("F")),
                                    GetContent(list)
                                    )
                            )));
                doc.Save(path);
            }
        }
        private static object[] GetContent(List<long> list){
            List<object> obj = new List<object>();
            foreach (var item in list)
	        {
		        obj.Add(new XElement("InsertTicketID",item.ToString()));
	        }
            return obj.ToArray();
        }

        /// <summary>
        /// 获取某人的插入历史
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="doc"></param>
        /// <returns></returns>
        private static XElement GetInsertHistory(string userName,XDocument doc){
            XElement user = (from use in doc.Descendants("InsertHistory").Where(w=>w.Element("User").Attribute("id").Value.Equals(userName)) select use).SingleOrDefault();
           return user;
        }
        /// <summary>
        /// 获取上传的历史记录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public static List<string> GetImportHistory(string userName,string path)
        {
            List<string> importHistory = new List<string>();
            if (File.Exists(path))
            {
                XDocument doc = XDocument.Load(path);
                var importLog = from user in doc.Descendants("User").
                    Where(w => w.Attribute("id").Value.Equals(userName))
                    select user;
                foreach (XElement item in importLog)
	            {
                    foreach (var date in item.Elements("Log"))
                    {
                        string value = date.Value;
                        importHistory.Add(value);
                    } 
	            }
            }
            else
            {
                return null;
            }
            return importHistory;
        }

        /// <summary>
        /// 创建声明
        /// </summary>
        /// <param name="path"></param>
        private static void CreateDeclaration(string path){
            xmldoc.AppendChild(xmldoc.CreateXmlDeclaration("1.0", "utf-8", null));
            //Create the root node and append into doc
            var el = xmldoc.CreateElement("InsertHistory");
            xmldoc.AppendChild(el);
            xmldoc.Save(path);
        }


        /// <summary>
        /// 是否包含该上传者
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        //public static bool ContainNode(string userId)
        //{
        //    xmldoc.SelectSingleNode("/")
        //    XmlElement rootElement = xmldoc.GetElementById(userId);
        //    if (rootElement != null)
        //    {
        //        userElement = rootElement;
        //        return true;
        //    }
        //    return false;
        //}
        /// <summary>
        /// 创建User节点
        /// </summary>
        /// <param name="entityName"></param>
        /// <param name="userID"></param>
        //private static void CreateRoot(string entityName,string userID)
        //{
        //    //创建User
        //    userElement = xmldoc.CreateNode(XmlNodeType.Element,entityName,null);
        //    userElement.SetAttribute("id", userID);
        //    xmldoc.AppendChild(userElement);
        //}
       /// <summary>
       /// 创建实体节点
       /// 
       /// </summary>
       /// <param name="list"></param>
        //public static void CreateEntity(List<long> list)
        //{
            
        //    //创建Log节点
        //    XmlElement logElement = xmldoc.CreateElement("Log");
        //    logElement.SetAttribute("id", (LogID++).ToString());
        //    userElement.AppendChild(logElement);
        //    //添加Log的子节点
        //    XmlElement dateElement = xmldoc.CreateElement("ImportDate");
        //    dateElement.InnerText = DateTime.Now.ToString();
        //    logElement.AppendChild(dateElement);
        //    XmlElement countElement = xmldoc.CreateElement("InsertCount");
        //    countElement.InnerText = list.Count.ToString();
        //    logElement.AppendChild(countElement);
        //    //创建插入的ticketID
        //    for (int i = 0; i < list.Count; i++)
        //    {
        //        XmlElement idElement = xmldoc.CreateElement("InsertTicketID");
        //        idElement.InnerText = list[i].ToString();
        //        logElement.AppendChild(idElement);
        //    }


        }


    
}